import qs from 'qs'
import pinia from '@/store'
import { isNull } from '@/utils/index'

const request = ({
  url,
  method = 'GET',
  data = {}
}) => {
  const header = {}
  header['Content-Type'] = 'application/x-www-form-urlencoded'
  if (!isNull(pinia.userStore.userInfo)) {
    header['tenantId'] = pinia.userStore.userInfo.tenantId
    header['userId'] = pinia.userStore.userInfo.id
  }
  const dataForm = qs.stringify(data, { allowDots: true })
  return new Promise((resolve, reject) => {
    uni.request({
      url: process.env.config[process.env.NODE_ENV].VITE_APP_BASE_API + url,
      data: dataForm,
      method,
      success(res) {
        if (!res.data.success) {
          uni.showToast({
            title: res.data.msg,
            icon: 'error'
          })
        }
        resolve(res)
      },
      fail(err) {
        uni.showToast({
          title: '请求异常',
          icon: 'error'
        })
        reject(err)
      },
      header: header
    })
  })
}

export default request
